package samples;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * 错误尝试封装
 */
public class RetryWithDelay implements Function<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelaySeconds;
    private int retryCount;

    public RetryWithDelay(final int maxRetries, final int retryDelaySeconds) {
        this.maxRetries = maxRetries;
        this.retryDelaySeconds = retryDelaySeconds;
        this.retryCount = 0;
    }

    @Override
    public Observable<?> apply(Observable<? extends Throwable> throwableObservale) {
        return throwableObservale.flatMap(new Function<Throwable, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(Throwable throwable) throws Exception {
                if (++retryCount < maxRetries) {
                    return Observable.timer(retryDelaySeconds, TimeUnit.SECONDS);
                }
                return Observable.error(throwable);
            }
        });
    }

    public int getRetryCount() {
        return retryCount;
    }
}
